package com.cn.base.事务;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author: dlr
 * @data: 2019/8/18 23:37
 * @desc:消费者事务
 */
public class consumerTration {
    private final static String MQ_URL="tcp://192.168.10.20:61616";
    //点对点对队列名
    private final static String QUEUE_NAME="BASE_QUEUE";

    public static void main(String[] args) throws Exception {
        //连接工厂
        ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory(MQ_URL);
        //获取连接
        Connection connection=factory.createConnection();
        //启动
        connection.start();
        //创建session
        //参数1:是否开启事务,参数2:签收模式
        Session session=connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        //创建消息目的地点对点队列
        Queue queue = session.createQueue(QUEUE_NAME);
        //创建消费者
        MessageConsumer consumer = session.createConsumer(queue);
        //监听队列
        consumer.setMessageListener(new MessageListener(){
            @Override
            public void onMessage(Message message) {
                TextMessage msg =(TextMessage)message;
                try{
                    if(msg!=null){
                        System.err.println(msg.getText());
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}
